# -- coding: utf-8 --
import os

import cv2
from pykeyboard import PyKeyboard
from pymouse import PyMouse

from wnboss05.tools.util import Base


class UI:
    driver = None

    @classmethod
    def get_driver(cls, browser):
        """
        通过单例模式获取浏览器驱动对象
        :param browser: 浏览器名称字符串
        :return: 浏览器驱动对象
        """
        from selenium import webdriver
        # 判断driver是否为空，为空证明是第一次打开浏览器，这时候需要实例化对象；如果不为空，则直接返回即可，不需要重新实例化
        if cls.driver is None:
            if hasattr(webdriver, browser):
                cls.driver = getattr(webdriver, browser)()
            else:
                cls.driver = webdriver.Firefox()
            cls.driver.implicitly_wait(5)
            cls.driver.maximize_window()
        return cls.driver

    @classmethod
    def get(cls, url):
        """
        打开一个url页面
        :param url: 页面地址
        :return: None
        """
        cls.driver.get(url)

    @classmethod
    def close(cls):
        """
        关闭当前页面
        :return:None
        """
        cls.driver.quit()
        cls.driver = None

    @classmethod
    def refresh(cls):
        """
        页面刷新
        :return:None
        """
        cls.driver.refresh()

    @classmethod
    def get_element(cls, locator):
        """
        根据定位方式来查找元素对象，如果找不到返回None
        :param locator:元素定位方式，格式为locator = {'by':'ID','what':'xxx'}
        :return:
        """
        by = locator['by']
        what = locator['what']
        try:

            from selenium.webdriver.common.by import By
            return cls.driver.find_element(getattr(By, by), what)
        except Exception as e:  # 没有找到，返回异常转回None
            return None

    @classmethod
    def input(cls, locator, value): # locator = ({'by':'ID','what':'xxx'},'woniu123')
        """
        向文本框元素输入内容
        :param locator: 定位方式
        :param value: 要输入的值
        :return: None
        """
        element = cls.get_element(locator)
        element.click()
        element.clear()
        element.send_keys(value)

    @classmethod
    def click(cls, locator): # locator = {'by':'ID','what':'xxx'}
        """
        点击某个元素
        :param locator:元素定位方式
        :return: None
        """
        element = cls.get_element(locator)
        element.click()

    @classmethod
    def select_option(cls,locator): # locator = {'by':'ID','what':'xxx'}
        """
        随机选择下拉数据某一项但不包括首行
        :param locator:
        :return:
        """
        element = cls.get_element(locator)
        from selenium.webdriver.support.select import Select
        size = len(Select(element).options)
        import random
        random_index = random.randint(1, size - 1)
        Select(element).select_by_index(random_index)

    @classmethod
    def exists(cls, locator):
        """
        判断某个元素是否存在，如果存在则返回True，否则返回False
        :param locator:元素定位器
        :return:boolean类型
        """
        if cls.get_element(locator) is None:
            return False
        else:
            return True

    @classmethod
    def screenshot(cls, version):
        """
        现场截图
        :return: None
        """
        version_path = f'../report/{version}'
        Base.create_dir(version_path)
        img_path = f'{version_path}/img'
        Base.create_dir(img_path)
        filename = f'{img_path}/{Base.get_time("%Y%m%d%H%M%S")}.png'
        png_path = f'./img/{Base.get_time("%Y%m%d%H%M%S")}.png'
        cls.driver.get_screenshot_as_file(filename)
        return png_path


class ImgMatchUtil:  # 会调用  图像匹配类

    mouse = PyMouse()
    keyboard = PyKeyboard()

    @classmethod
    def match_img(cls, target):
        """
        匹配图像方法，返回找到的图像的坐标，如果没找到则返回-1，-1
        :param target:
        :return:
        """
        image_path = '../image'
        template_path = os.path.join(image_path, target)
        screen_path = os.path.join(image_path, 'screen.png')
        from PIL import ImageGrab
        ImageGrab.grab().save(screen_path)

        # 读取大图
        screen = cv2.imread(screen_path)
        # 读取小图
        template = cv2.imread(template_path)
        # 调用匹配算法
        result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)

        min, max, min_loc, max_loc = cv2.minMaxLoc(result)

        # 计算矩形十字中心点的坐标
        x = max_loc[0] + int(template.shape[1] / 2)
        y = max_loc[1] + int(template.shape[0] / 2)

        # 如果没匹配成功，则返回的是-1，-1
        return x, y

        # 单击图片元素
    @classmethod
    def click_image(cls, target):
        x, y = cls.match_img(target)
        print(x, y)
        if x == -1 and y == -1:
            return
        cls.mouse.click(x, y)

    # 双击图片元素
    @classmethod
    def double_click_image(cls, target):
        x, y = cls.match_img(target)
        if x == -1 and y == -1:
            return
        cls.mouse.click(x, y, n=2)

    # 向一个文本框图片输入
    @classmethod
    def input_image(cls, target, value):
        x, y = cls.match_img(target)
        if x == -1 and y == -1:
            return
        cls.keyboard.type_string(value)

if __name__ == '__main__':

    UI.get_driver('Browser')
    UI.get('http://192.168.44.128:8080/WoniuBoss4.0')
    UI.screenshot('v0.6')
    # <img src="img/20230304120013.png">